package com.zhichat.infrastructure.util;

import java.util.SortedMap;
import java.util.TreeMap;

public class ConsistentHash {
    private static Integer[] clock_scale = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
    private static SortedMap<Integer, Integer> sortedMap = new TreeMap<>();

    static {
        for (Integer scale : clock_scale) {
            sortedMap.put(getHash(String.valueOf(scale)), scale);
        }
    }


    private static int getHash(String str) {
        final int p = 16777619;
        int hash = (int) 2166136261L;
        for (int i = 0; i < str.length(); i++)
            hash = (hash ^ str.charAt(i)) * p;
        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;
        if (hash < 0)
            hash = Math.abs(hash);
        return hash;
    }



    private static Integer getNode(String str) {
        int hash = getHash(str);
        SortedMap<Integer, Integer> subMap = sortedMap.tailMap(hash);
        Integer i = subMap.firstKey();
        return subMap.get(i);
    }


    public static int getDuration(String str) {
        return getNode(str) << 3;
    }
}
